package com.caregiver.watch.common.config;

import org.apache.shardingsphere.driver.api.ShardingSphereDataSourceFactory;
import org.apache.shardingsphere.driver.api.yaml.YamlShardingSphereDataSourceFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

import javax.sql.DataSource;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;

@Configuration
public class ShardingConfig {


    // 获取到环境
    @Value("${spring.profiles.active}")
    private String ENV;

    @Bean
    public DataSource sharding(ResourceLoader resourceLoader) throws SQLException, IOException {
        Resource resource = resourceLoader.getResource("classpath:sharding/sharding-sphere-config-" + ENV + ".yaml");
        try (InputStream inputStream = resource.getInputStream()) {
            return YamlShardingSphereDataSourceFactory.createDataSource(toByteArray(inputStream));
        }
    }

    /**
     * inputStream 转成 byte[]
     */
    public static byte[] toByteArray(InputStream inputStream) throws IOException {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        byte[] data = new byte[4096]; // 4KB 缓冲区
        int bytesRead;
        while ((bytesRead = inputStream.read(data, 0, data.length)) != -1) {
            buffer.write(data, 0, bytesRead);
        }
        return buffer.toByteArray();
    }
}
